package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/20 9:17
 * Version:1.0-SNAPSHOT
 * Description: 编写黑名单过滤器
 * 在当前过滤器中设置初始化参数
 * 将所有的黑名单人员的ip地址在初始化参数中进行配置
 * 且黑名单人员数量不定,随时可以CURD
 * 在功能完成之后,后期如果需要对黑名单人员数量进行操作的时候
 * 无需修改具体代码,只需要修改初始化参数的配置即可生效
 * 黑名单里面的值是ip地址,访问者的ip地址
 * 如果黑名单人员访问了,则给出一个页面提示:你属于黑名单用户,请先解除黑名单
 */
//@WebFilter(urlPatterns = "/*",initParams = {
//        @WebInitParam(name = "blackList",value = "192.168.6.8")
//})
public class BlackListFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("*************BlackListFilter.doFilter");
        String blackList = config.getInitParameter("blackList");
        // 在初始化参数中配置的黑名单的值是一系列的ip地址
        // 这些ip地址之间以逗号分隔
        // 通过逗号分隔可以获取一个ip的数组
        String[] ips = blackList.split(",");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取访问者的ip地址
        String ip = request.getRemoteAddr();
        System.out.println("当前访问者的ip地址:"+ip);
        // 判断黑名单的数组中是否包含当前的访问者ip
        for(String s : ips){
            if(ip.equals(s)){
                PrintWriter out = response.getWriter();
                out.print("<h1 style='color:red;'>你属于黑名单用户,请先解除黑名单</h1>");
                return;
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
